#关机并删除虚拟机
killallVM() {
  
 for i in $(virsh list --all | awk 'NR>1{print $2}') ; do
   virsh destroy $i &> /dev/null
   virsh undefine $i &> /dev/null
 done
 rm -rf /var/lib/libvirt/images/*
 rm -rf /etc/libvirt/qemu/vm*
}


#批量创建虚拟机

createvm(){
  for i in $(seq -f "%02g" $VMnumber); do
   	vm_name=vm${i}_centos79
   	vm_mac=52:54:00:$(openssl rand -hex 3 | sed  "s/\(..\)/\1:/g; s/.$//")
    	cp /bash/base.xml /etc/libvirt/qemu/${vm_name}.xml
    	qemu-img create -f qcow2 -b /bash/base.qcow2 /var/lib/libvirt/images/${vm_name}.qcow2 &> /dev/null
   
    	sed -ri "s/centos79/${vm_name}/g" /etc/libvirt/qemu/${vm_name}.xml
    	sed -ri "/uuid/c \  <uuid>$(uuidgen)</uuid>" /etc/libvirt/qemu/${vm_name}.xml
    	sed -ri "/<mac/c \    <mac address='${vm_mac}'/>" /etc/libvirt/qemu/${vm_name}.xml
    
    	virsh define /etc/libvirt/qemu/${vm_name}.xml  #&> /dev/null 
  done
}

 while true;do
 cat << EOF
 ==========配置虚拟机管理===========
 1.删除全部虚拟机（磁盘一起删）
 2.创建多个虚拟机
 3.先删除全部虚拟机再创建多个虚拟机
 4.退出
EOF

read -p "请输入选项：" number
 case $number in
   1)
    echo ------------------------
    echo "开始删除虚拟机"
    echo ------------------------
    killallVM
    echo 
    echo $(virsh list --all)
    echo ------------------------
    ;;
   2)
    read -p "请输入要创建几台虚拟机:"  VMnumber
    sleep 2
    createvm
    echo $(virsh list --all) 
      ;;
   3)
    killallVM
    echo "正在删除虚拟机"
    sleep 2
    read -p "请输入要创建几台虚拟机:"   VMnumber
    createvm
    echo $(virsh list --all) 
    ;;
   4)
     exit 0
    ;;
 esac
done
